<template>
  <div class="box">
    <el-row class="btn-row">
      <el-button type="text" @click="dialogFormVisible = true"
        >发布动态</el-button
      >
    </el-row>
    <!-- 展示已发布的动态 -->
    <el-table :data="userOwnBlog" style="width: 100%">
      <el-table-column prop="title" label="文章标题" width="180">
      </el-table-column>
      <el-table-column prop="blogtime" label="发布时间" width="180">
      </el-table-column>
      <el-table-column prop="content" label="内容">
        <template slot-scope="scope">
          <div class="table-cell-content">{{ scope.row.content }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="agree" label="已经获赞数"> </el-table-column>
      <el-table-column label="操作" fixed="right" width="100">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            @click="toDetail(scope.row.postid)"
            >查看</el-button
          >
          <el-button
            type="text"
            size="small"
            @click="handleDelete(scope.row.postid)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 确认框 -->
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <span>确认删除吗</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmDelete">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分页器 -->
    <div class="block">
      <el-pagination
        layout="prev, pager, next"
        :current-page="pageInfo.pageNum"
        @current-change="handleCurrentChange"
        :page-size="pageInfo.pageSize"
        :hide-on-single-page="true"
        :total="pageInfo.total"
      >
      </el-pagination>
    </div>
    <!-- 发布动态dialog -->
    <el-dialog title="发表动态" :visible.sync="dialogFormVisible">
      <el-form :model="blogForm.blog">
        <el-form-item label="输入题目" :label-width="formLabelWidth">
          <el-input v-model="blogForm.blog.title" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="上传图片"
          :label-width="formLabelWidth"
          class="imgbox"
        >
          <el-upload
            :multiple="multiple"
            action="#"
            :limit="3"
            list-type="picture-card"
            :auto-upload="false"
            :on-change="uploadFile"
            ref="upload"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="正文内容" :label-width="formLabelWidth">
          <el-input
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4 }"
            placeholder="请输入内容"
            v-model="blogForm.blog.content"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {AddBlog,GetOwnBlogByPage,DeleteBlog} from '../../../request/api'
import {mapActions,mapState,mapMutations} from 'vuex'
export default {
    data() {
      return {
        dialogFormVisible: false,
        multiple:true,
        blogForm:{
          blog:{
            title: '',
            blogtime:'',
            content: '',
            blogimg:'',
            agree:0,
            disagree:0
          },
          file:[]
        },
        formLabelWidth: '120px',
        params:{
          pageNum:null,
          blogid:null
        },
        pageInfo:{},
        dialogVisible: false
      }
    },
    computed:{
      ...mapState({
        userOwnBlog:state=>state.blogStatus.userOwnBlog,
        // pageNum:state=>state.blogStatus.pageNum,
      })
    },
    methods: {
            ...mapActions({
              asyncChangeIsShowToast:'toastStatus/asyncChangeIsShowToast'
            }),
            ...mapMutations({
              setUserOwnBlog:'blogStatus/setUserOwnBlog',
              addUserOwnBlog:'blogStatus/addUserOwnBlog',
              // setPageNum:'blogStatus/setPageNum'
            }),
            uploadFile(file){
              let formData = new FormData()
              this.blogForm.file.push(file)
            },
            async handleSubmit(){
              // 发送请求
              // this.param = this.blog
              // this.param.blogimg = this.blogform.blogimg.map(item=>item.raw).toString()
              const allKey  = Object.keys(this.blogForm.blog)
              const f = new FormData()
              const allFiles = this.blogForm.file.forEach(item=>{
                f.append('file',item.raw)
              })
              for(let key of allKey){
                f.append(key,this.blogForm.blog[key])
              }
              let res = await AddBlog(f)
              if(res.data.state == 200){
                // 成功
                this.asyncChangeIsShowToast({
                  msg:'发布成功！',
                  type:'success'
                })
              }else{
                // 失败
                this.asyncChangeIsShowToast({
                  msg:'发布失败',
                  type:'error'
                })
              }
              // 刷新表单
              let res2  = await GetOwnBlogByPage(this.params)
              this.setUserOwnBlog(res2.data.data.list)
              this.pageInfo = res2.data.data
              // 隐藏表单
              this.dialogFormVisible = false

            },
            async handleCurrentChange(pageNum){
              this.params.pageNum = pageNum
              // 发送请求
              let res = await GetOwnBlogByPage({pageNum})
              // 更新数据
              this.setUserOwnBlog(res.data.data.list)

            },
            async handleDelete(blogid){
              this.params.blogid = blogid
              this.dialogVisible = true
            },
            async confirmDelete(){
              let res = await DeleteBlog(this.params)
              if(res.data.state == 200){
                this.asyncChangeIsShowToast({
                  msg:'删除成功',
                  type:'success'
                })
              }
              this.userOwnBlog.length === 1 && this.params.pageNum--
              if (this.params.pageNum < 1){
                this.params.pageNum = 1
              }
              // 刷新页面数据
              this.dialogVisible = false
              // this.params.pageNum = this.pageNum
              // console.log('pageNum',this.params);
              let res2 = await GetOwnBlogByPage(this.params)
              this.setUserOwnBlog(res2.data.data.list)
              this.pageInfo = res2.data.data
            },
            toDetail(blogid){
              this.$router.push({
                path:'/home/detail',
                query:{
                  blogid,
                  userid:sessionStorage.getItem('userid')
                }
              })
            },
            handleClose(done) {
                this.$confirm('确认关闭？')
                  .then(_ => {
                    done();
                  })
                  .catch(_ => {});
            }
          },
    async created(){
      this.params.pageNum = 1
      // this.setPageNum(1)
      // 发请求获取分页数据
      let res =await GetOwnBlogByPage(this.params)
      this.setUserOwnBlog(res.data.data.list)
      this.pageInfo = res.data.data
    },

  };
</script>

<style scoped>
.btn-row {
  display: flex;
  flex-direction: row-reverse;
  margin-right: 20px;
}
.imgbox {
  height: 150px !important;
  overflow: hidden;
}
.box {
  display: flex;
  flex-direction: column;
}
.block {
  margin: 0 auto !important;
}
.table-cell-content {
  white-space: nowrap; /* 防止内容换行 */
  overflow: hidden; /* 超出部分隐藏 */
  text-overflow: ellipsis; /* 超出部分显示省略号 */
}
</style>
